import { supabase } from '../config/supabase'
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus'
import Mock from 'mockjs'

const TABLE_NAME = 'students'

// 生成模拟数据
const generateMockStudents = (count = 100) => {
  const students = []
  const schools = ['北京大学', '清华大学', '复旦大学', '浙江大学', '南京大学', '武汉大学', '上海交通大学', '中国人民大学']
  const classes = ['高一(1)班', '高一(2)班', '高二(3)班', '高二(4)班', '高三(5)班', '高三(6)班']
  const groups = ['A组', 'B组', 'C组', 'D组']
  const teachers = ['张老师', '王老师', '李老师', '赵老师', '刘老师']

  for (let i = 1; i <= count; i++) {
    // 生成基本信息
    const student = {
      id: i,
      account: `student${i}`,
      name: Mock.Random.cname(),
      phone: Mock.Random.string('number', 11),
      school: Mock.Random.pick(schools),
      class: Mock.Random.pick(classes),
      group: Mock.Random.pick(groups),
      teacher: Mock.Random.pick(teachers),
      points: Mock.Random.integer(0, 1000),
      expireTime: Mock.Random.date('yyyy-MM-dd'),
      createTime: Mock.Random.date('yyyy-MM-dd'),
      updateTime: Mock.Random.date('yyyy-MM-dd')
    }
    students.push(student)
  }
  return students
}

// 模拟学生数据
let mockStudents = generateMockStudents()

export const studentService = {
  // 获取学生列表
  async getStudents({ page = 1, pageSize = 10, filters = {} } = {}) {
    // 处理延迟模拟网络请求
    await new Promise(resolve => setTimeout(resolve, 500))

    // 过滤数据
    let filteredData = [...mockStudents]

    // 处理过滤条件
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase()
      filteredData = filteredData.filter(student => 
        student.name.toLowerCase().includes(keyword) || 
        student.account.toLowerCase().includes(keyword) ||
        student.phone.includes(keyword)
      )
    }

    if (filters.school) {
      filteredData = filteredData.filter(student => student.school === filters.school)
    }

    if (filters.class) {
      filteredData = filteredData.filter(student => student.class === filters.class)
    }

    if (filters.teacher) {
      filteredData = filteredData.filter(student => student.teacher === filters.teacher)
    }

    if (filters.expireDateRange && filters.expireDateRange.length === 2) {
      const [startDate, endDate] = filters.expireDateRange
      filteredData = filteredData.filter(student => {
        const expireDate = new Date(student.expireTime)
        return expireDate >= startDate && expireDate <= endDate
      })
    }

    // 计算分页数据
    const total = filteredData.length
    const startIndex = (page - 1) * pageSize
    const endIndex = startIndex + pageSize
    const data = filteredData.slice(startIndex, endIndex)

    return { data, total }
  },

  // 删除学生
  async deleteStudents(ids) {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    mockStudents = mockStudents.filter(student => !ids.includes(student.id))
    return { success: true }
  },

  // 批量分配
  async batchAssign(ids, assignData) {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    mockStudents = mockStudents.map(student => {
      if (ids.includes(student.id)) {
        return {
          ...student,
          ...assignData
        }
      }
      return student
    })
    
    return { success: true }
  },

  // 添加学生
  async addStudent(studentData) {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 检查账号是否已存在
    const existingAccount = mockStudents.find(s => s.account === studentData.account)
    if (existingAccount) {
      throw new Error('该账号已被使用')
    }
    
    const newStudent = {
      ...studentData,
      id: mockStudents.length + 1,
      createTime: new Date().toISOString().split('T')[0],
      updateTime: new Date().toISOString().split('T')[0]
    }
    
    mockStudents.push(newStudent)
    return { success: true, data: newStudent }
  },

  // 更新学生
  async updateStudent(id, studentData) {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 如果修改了账号，检查是否与其他学生重复
    if (studentData.account) {
      const existingAccount = mockStudents.find(s => s.account === studentData.account && s.id !== id)
      if (existingAccount) {
        throw new Error('该账号已被使用')
      }
    }
    
    mockStudents = mockStudents.map(student => {
      if (student.id === id) {
        return {
          ...student,
          ...studentData,
          updateTime: new Date().toISOString().split('T')[0]
        }
      }
      return student
    })
    
    return { success: true }
  },

  // 激活学生
  async activateStudents(ids, activeDays) {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const today = new Date()
    
    mockStudents = mockStudents.map(student => {
      if (ids.includes(student.id)) {
        // 计算新的到期时间
        let expireDate = new Date(student.expireTime)
        // 如果已过期，从今天开始计算
        if (expireDate < today) {
          expireDate = new Date()
        }
        expireDate.setDate(expireDate.getDate() + activeDays)
        
        return {
          ...student,
          expireTime: expireDate.toISOString().split('T')[0],
          updateTime: today.toISOString().split('T')[0]
        }
      }
      return student
    })
    
    return { success: true }
  },

  // 更新积分
  async updatePoints(ids, points) {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    mockStudents = mockStudents.map(student => {
      if (ids.includes(student.id)) {
        return {
          ...student,
          points,
          updateTime: new Date().toISOString().split('T')[0]
        }
      }
      return student
    })
    
    return { success: true }
  },

  // 导出学生数据
  async exportStudents() {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('学生数据已导出')
    
    // 实际导出逻辑会保存文件，这里只做模拟
    console.log('导出学生数据', mockStudents)
    
    return { success: true }
  },

  // 获取即将到期的学生列表
  async getExpiringStudents(days = 30, filters = {}) {
    try {
      let query = supabase
        .from(TABLE_NAME)
        .select(`
          *,
          classes:class_id(name),
          groups:group_id(name)
        `)
        .lte('expire_time', new Date(Date.now() + days * 24 * 60 * 60 * 1000).toISOString())

      // 添加过滤条件
      if (filters.account) {
        query = query.ilike('account', `%${filters.account}%`)
      }
      if (filters.name) {
        query = query.ilike('name', `%${filters.name}%`)
      }
      if (filters.phone) {
        query = query.ilike('phone', `%${filters.phone}%`)
      }
      if (filters.classId) {
        query = query.eq('class_id', filters.classId)
      }

      query = query.order('expire_time', { ascending: true })

      const { data: rawData, error } = await query

      if (error) throw error

      // 处理响应数据
      const data = rawData.map(student => {
        const expireTime = new Date(student.expire_time)
        const now = new Date()
        const remainingDays = Math.ceil((expireTime - now) / (1000 * 60 * 60 * 24))

        return {
          ...student,
          class: student.classes?.name || '-',
          group: student.groups?.name || '-',
          expireTime: expireTime.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          }),
          remainingDays
        }
      })

      return { data }
    } catch (error) {
      throw error
    }
  },

  // 获取课程分配用的学生列表
  async getStudentsForCourse({ page = 1, pageSize = 10, filters = {} }) {
    // 处理延迟模拟网络请求
    await new Promise(resolve => setTimeout(resolve, 500))

    // 过滤数据
    let filteredData = [...mockStudents]

    // 处理过滤条件
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase()
      filteredData = filteredData.filter(student => 
        student.name.toLowerCase().includes(keyword) ||
        student.account.toLowerCase().includes(keyword) ||
        student.phone.includes(keyword) ||
        student.school.toLowerCase().includes(keyword) ||
        student.class.toLowerCase().includes(keyword)
      )
    }

    if (filters.school) {
      filteredData = filteredData.filter(student => student.school === filters.school)
    }

    if (filters.class) {
      filteredData = filteredData.filter(student => student.class === filters.class)
    }

    if (filters.teacher) {
      filteredData = filteredData.filter(student => student.teacher === filters.teacher)
    }

    // 分页处理
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const paginatedData = filteredData.slice(start, end)

    return {
      data: paginatedData,
      total: filteredData.length
    }
  }
}

// 导出一些辅助数据供组件使用
export const studentOptions = {
  schools: [...new Set(mockStudents.map(s => s.school))],
  classes: [...new Set(mockStudents.map(s => s.class))],
  teachers: [...new Set(mockStudents.map(s => s.teacher))],
  groups: [...new Set(mockStudents.map(s => s.group))]
}
